/***
 **广告词弹出框
 **/
define(['../model/data','../common/service'],function(DATA,http){
    return function(){
        var which;
        var  langId = -1;
        var  lan = "";
        var  foId = DATA.app.fbConnectionObjectId;

        //保存广告语
        $("button.save-slogan").unbind("mousedown").mousedown(function(){
            var self = this;
            var the = $("body>div.modal.common-modal");
            the.dialog({
                id:$(this).data("target").replace("#",""),
                label:$(this).data("label"),
                title : I18N.getText('createAd','saveAdword'),
                body:'<div class="new-save-slogan">\
                <div class="save-layer"><span>'+I18N.getText('createAd', 'languages')+'</span>\
                <div name="save-lang-drop" style="margin-left:15px;width:60%;display: inline-block;">\
              <select class="save-adword-lan-drop form-control" tabindex="-1" style="width:100%" aria-hidden="true"></select>\
              </div>\
                </div>\
                <div class="save-layer"><span class="save-comment">'+I18N.getText('createAd', 'remark')+'</span>\
                <textarea class="new-save-content" maxlength="50"></textarea>\
                </div>\
                <div class="text-range-warning"></div></div>'
            }).off("ok").on("ok",function(e,o){
                //校验保证  在dialog，TODO 此组件不通用，需要修改
                var txt = $(self).parent().parent().find("textarea").val();
                var body =DATA.body([{key:"word",value:txt},
                    {key:"fbConnectionObjectId",value:DATA.app.fbConnectionObjectId},
                    {key:"fbConnectionObjectName",value:DATA.app.name},
                    {key:"languageId",value: o.languageId},
                    {key:"language",value: o.language},
                    {key:"description",value:o.desc}]);
                http.do("/adwords/createAdword",body);
            });

            //渲染语言下拉列表
            var langHtml = '<option value="-1">'+I18N.getText('createAd', 'optionPlsLanguage')+'</option>';
            $.each(DATA.adwordLangs, function(i,lang){
                langHtml += '<option value="'+(lang.id || '')+'">'
                    + lang.name
                    + '</option>';
            });
            var _adwordLang = $(".save-adword-lan-drop");
            _adwordLang.html(langHtml);
            _adwordLang.select2({minimumResultsForSearch: Infinity}).select2("val", -1);

            //给备注绑定事件
            the.find("textarea").off("input").on('input', function(e){
                e.stopImmediatePropagation();
                var len = $(this).val().length;
                if(len == 0){
                    the.find(".text-range-warning").text("");
                }else if(len < 50){
                    the.find(".text-range-warning").text(I18N.getText('createAd', 'adWordCanInput')+(50-len)+" "+I18N.getText('createAd', 'adWordCharacters'));
                }else{
                    the.find(".text-range-warning").text(I18N.getText('createAd', 'adWordMaxLength'));
                }

                if (kit.isAr($(this).val())) {
                    $(this).attr('dir', 'rtl');
                } else {
                    $(this).removeAttr('dir', 'rtl');
                }
            });

            //每次弹出需要清空备注
            $(".new-save-content").val('');
            $(".new-save-content").trigger("input");
            $('div[name="save-lang-drop"]').removeClass("anim_image_glow");
        });

        //导入广告语
        $("button.import-slogan").unbind("mousedown").mousedown(function(e){
            which = $(this);
            var txtIndex = which.parents("li").index();
            $("body>div.modal.common-modal").dialog({
                id:$(this).data("target").replace("#",""),
                label:$(this).data("label"),
                height: 500,
                title : I18N.getText('createAd','importAdword'),
                body:'<div class="sc-select-btn">\
                <select class="adword-app-drop-selector form-control" tabindex="-1" style="width:40%;" aria-hidden="true"></select>\
                <select class="adword-lan-drop-selector form-control" tabindex="-1" style="width:40%;" aria-hidden="true"></select>\
                <button name="adword-search" class="btn btn-primary input-button">'+ I18N.getText('createAd','search') +'</button>\
                </div>\
                <div class="adword-list">\
                <table class="table table-bordered table-hover nowrap-ellipsis">\
                <thead>\
                <tr>\
                <th width="45">'+ I18N.getText('common','select') +'</th>\
                <th width="50">'+ I18N.getText('common','order') +'</th>\
                <th>'+ I18N.getText('createAd','adword') +'</th>\
                </tr>\
                </thead>\
                <tbody>\
                </tbody>\
                </table>'
            }).unbind("ok").on("ok",function(e,o){//用户选择了广告词
                DATA.adTags = [];
                DATA.adWords[txtIndex] = o.word;
                which.parent().parent().find(".adWordField").val(o.word).trigger("input");
            });

            //初始化应用
            var ar = (function(){var tmp = [].concat(DATA.apps); tmp.shift();   return tmp;}());
            var appHtml = '<option value="-1">'+I18N.getText('createAd', 'optionPlsApp')+'</option>';
            for(var i = 0; i< ar.length; i++){
                appHtml += '<option value="'+(ar[i].fbConnectionObjectId || '')+'">'
                    + ar[i].name
                    + '</option>'
            }
            var _adwordApp = $(".adword-app-drop-selector");
            _adwordApp.html(appHtml);
            _adwordApp.select2().unbind("select2:select").on("select2:select",function(e){
                //设置当前应用Id
                foId = e.params.data.id;
                langId = -1;
                var fbConnectionObjectId = e.params.data.id;
                //根据应用查询语言
                searchLanguage(fbConnectionObjectId);
            }).select2("val",(DATA.app.fbConnectionObjectId)||-1);

            searchLanguage(DATA.app.fbConnectionObjectId);

            //用户点击搜索按钮
            $("button[name='adword-search']").unbind("click").click(function(){
                wordList($(".adword-app-drop-selector").select2("val"), $(".adword-lan-drop-selector").select2("val"));
            });

            //默认加载当前应用下所有语言的广告词
            wordList(DATA.app.fbConnectionObjectId, -1);
        });

        //根据应用查询语言
        function searchLanguage(_fbConnectionObjectId){
            //根据应用关联语言
            var param = DATA.body([{key:"fbConnectionObjectId",value:_fbConnectionObjectId}]);
            param.dicType = 'adword';
            http.do("/adwords/searchLanguage",param,"GET").then(function(result){
                if(typeof(result)=="string") result = JSON.parse(result);
                var da = result.data;
                var langHtml = '<option value="-1">'+I18N.getText('createAd', 'optionPlsLanguage')+'</option>';
                $.each(da, function(i,lang){
                    langHtml += '<option value="'+(lang.id || '')+'">'
                        + lang.name
                        + '</option>';
                });

                var _adwordLang = $(".adword-lan-drop-selector");
                _adwordLang.html(langHtml);
                _adwordLang.select2({minimumResultsForSearch: Infinity}).select2("val", -1);
            },function(err){});
        }

        //列表 请求列表
        function wordList(_fbConnectionObjectId, _languageId){
            var the = $("body>div.modal.common-modal");
            the.find(".adword-list>tbody").remove();// reset

            var body = DATA.body([{key:"fbConnectionObjectId",value:_fbConnectionObjectId},
                {key:"languageId",value:_languageId}]);
            http.do("/adwords/getAdwordsAllList",body,"GET").then(function(result){
                if(typeof(result)=="string") result = JSON.parse(result);
                var da = result.data;
                var html='';
                for(var i=0;i<da.length;i++){
                    html += '<tr>\
                       <td class="text-center"><input type="radio" name="adword-select" adword="' + da[i].word + '"></td>\
                       <td class="text-center">'+(i+1)+'</td>\
                       <td><span class="adword" title='+ da[i].word + '>' + da[i].word + '</span></br><span class="remark" title='+ (da[i].description || '') + '>' + (da[i].description || '') + '</span></td>\
                       </tr>';
                }
                the.find(".adword-list").find("tbody").html(html);
            },function(err){});
        }
    }
});
